package com.sljy.hzk.base;

import android.app.Application;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.sljy.hzk.MainActivity;
import com.sljy.hzk.R;
import com.sljy.hzk.annotation.ActivityInfo;
import com.sljy.hzk.entity.UserEntity;
import com.sljy.hzk.room.AppDataBase;
import com.sljy.hzk.ui.LoginActivity;
import com.sljy.hzk.util.AutoDensityUtils;
import com.sljy.hzk.util.EventListenerManager;
import com.sljy.hzk.util.NetWorkUtils;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created  on 2018/6/25 0025
 *
 * @author 唐开阔
 * @describe
 */
public abstract class BaseActivity extends RxAppCompatActivity {
    protected final String TAG = this.getClass().getSimpleName();
    private TextView tvTitle;
    private ImageView imageBack, imageRight;
    public Unbinder unbinder;
    private int width;
    private int height;
    TextView titleText;
    //public Bundle savedInstanceState;
    String FRAGMENTS_TAG = "android:support:fragments";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        /**
         * 不保存fragment实例，每次都新建
         */
        if (savedInstanceState != null) {
            savedInstanceState.putParcelable(FRAGMENTS_TAG, null);
        }
        //this.savedInstanceState = savedInstanceState;
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

//        if (Build.VERSION.SDK_INT >= 21){
//            View decorView = getWindow().getDecorView();
//            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
//            getWindow().setStatusBarColor(Color.TRANSPARENT);
//        }

        AutoDensityUtils.setCustomDensity(this);
        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        width = outMetrics.widthPixels;
        height = outMetrics.heightPixels;

        ActivityInfo activityInfo = getClass().getAnnotation(ActivityInfo.class);
//        if(!activityInfo.title().equals("") && !activityInfo.title().equals(null) ){
//            titleText = getWindow().findViewById(R.id.title_text);
//            titleText.setText(activityInfo.title());
//            imageBack = getWindow().findViewById(R.id.back_btn);
//            imageBack.setOnClickListener(v ->onBackClick());
//        }

        if (activityInfo.isFullscreen()) {
            this.requestWindowFeature(Window.FEATURE_NO_TITLE);
            this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
           // getSupportActionBar().hide();
        }

        setContentView(activityInfo.layout());
        unbinder = ButterKnife.bind(this);

        if (!activityInfo.isShowActionBar()) {
            //getSupportActionBar().hide();
        } else {
//            ActionBar actionBar = getSupportActionBar();
//            actionBar.setElevation(0);
//            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
//            actionBar.setCustomView(R.layout.top_style);
            Toolbar mToolbarTb = (Toolbar) findViewById(R.id.toolbar_normal);
            setSupportActionBar(mToolbarTb);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
            titleText = mToolbarTb.findViewById(R.id.title_text);
            imageRight = mToolbarTb.findViewById(R.id.right_btn);
            imageBack = mToolbarTb.findViewById(R.id.back_btn);
            //actionBar.setCustomView(activityInfo.titleLevel() == ActivityInfo.TITLE_ONE_LEVEL ?R.layout.layout_actionbar_one_level : R.layout.layout_actionbar_two_level);
//            titleText = mToolbarTb.getCustomView().findViewById(R.id.title_text);
//            imageRight = mToolbarTb.getCustomView().findViewById(R.id.right_btn);
//            imageBack = mToolbarTb.getCustomView().findViewById(R.id.back_btn);
            imageBack.setOnClickListener(v ->onBackClick());
            titleText.setText(activityInfo.title());
            if (activityInfo.rightIcRes() != ActivityInfo.NO_RIGHT_IC) {
                imageRight.setBackgroundResource(activityInfo.rightIcRes());
                //imageRight.setImageResource(activityInfo.rightIcRes());
                imageRight.setOnClickListener(v -> onRightClick());
                //if(!activityInfo.title().equals("危害因素"))
                   // imageRight.setVisibility(View.GONE);
                imageRight.setVisibility(View.VISIBLE);
            }else{
                imageRight.setVisibility(View.GONE);
            }
        }
        init();
        registEvent();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    /**
     * 初始化
     */
    protected abstract void init();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeEvent();
        unbinder.unbind();
    }
    public void setTitle(String title){
        titleText.setText(title);
    }

    protected void showToast(String mes) {
        Toast toast = Toast.makeText(this, mes, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP, 0, height / 4);
        toast.show();
    }

    protected void showToast(String mes, int imgId) {
        Toast tast=Toast.makeText(this, mes, Toast.LENGTH_LONG);
        tast.setGravity(Gravity.CENTER, 0, 0);
        View view=LayoutInflater.from(this).inflate(R.layout.toast_layout, null);
        TextView tvMsg=(TextView)view.findViewById(R.id.content);
        tvMsg.setText(mes);
        ImageView img = (ImageView)view.findViewById(R.id.img);
        img.setBackgroundResource(imgId);
        tast.setView(view);
        tast.show();
    }

    protected void showExitDialog(String mes, int imgId){
        Dialog dialog=new Dialog(this);//可以在style中设定dialog的样式
        dialog.setContentView(R.layout.dialog_layout);
        WindowManager.LayoutParams lp= dialog.getWindow().getAttributes();
        lp.gravity= Gravity.CENTER;
        lp.height= WindowManager.LayoutParams.WRAP_CONTENT;
        lp.width= WindowManager.LayoutParams.MATCH_PARENT;
        TextView tvMsg=(TextView)dialog.getWindow().findViewById(R.id.content);
        tvMsg.setText(mes);
        ImageView img =(ImageView)dialog.getWindow().findViewById(R.id.img);
        img.setBackgroundResource(imgId);
        ImageButton btOk=(ImageButton)dialog.getWindow().findViewById(R.id.yBtn);
        ImageButton btCancel=(ImageButton)dialog.getWindow().findViewById(R.id.nBtn);
        btCancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                OnDialogBtnClick(false);
                dialog.cancel();
            }
        });
        btOk.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                OnDialogBtnClick(true);
                dialog.cancel();
            }
        });
        dialog.getWindow().setAttributes(lp);
        //设置该属性，dialog可以铺满屏幕
        dialog.getWindow().setBackgroundDrawable(null);
        dialog.show();

    }


    protected void OnDialogBtnClick(boolean isSure){

    }


    /**
     * 返回点击事件
     */
    protected void onBackClick(){
        finish();
    }

    @Override
    public void onBackPressed() {
        if(!this.TAG.equals("MainActivity") && !this.TAG.equals("LoginActivity")){
            //super.onBackPressed();
            return;
        }
        new MaterialDialog.Builder(this)
            .content("是否退出应用")
            .positiveText("退出")
            .onPositive((dia, v) -> {
                super.onBackPressed();
            })
            .negativeText("取消")
            .onNegative((dialog, which) -> {

            })
            .show();
    }

    /**
     * 右图标点击事件
     */
    protected void onRightClick(){
        startActivity(MainActivity.class);
    }

    /**
     * 便捷指定线程
     * @param <T>
     * @return
     */
    public <T> ObservableTransformer<T, T> getThread() {
        return upstream -> upstream.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    }

    /**
     * 跳转
     * @param cla
     */
    public void startActivity(Class cla) {
       if(getCurrentFocus() == null){
           Intent intent = new Intent(this, cla);
           super.startActivity(intent);
           return;
       }
        ActivityOptionsCompat compat = ActivityOptionsCompat.makeScaleUpAnimation(this.getCurrentFocus(),
                this.getCurrentFocus().getWidth()/2, this.getCurrentFocus().getHeight()/2,0,0);
        ActivityCompat.startActivity(this,
                new Intent(this, cla), compat.toBundle());
    }

    /**
     * 点击键盘以外区域，收起键盘
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        try {
            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                View v = getCurrentFocus();
                if (isShouldHideInput(v, ev)) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    }
                }
                return super.dispatchTouchEvent(ev);
            }else if(ev.getAction() == MotionEvent.ACTION_UP){
                onClickUp();
            }
            // 必不可少，否则所有的组件都不会有TouchEvent了
            if (getWindow().superDispatchTouchEvent(ev)) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return onTouchEvent(ev);
        }
    }

    protected void onClickUp(){

    }

    protected boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                //使EditText触发一次失去焦点事件
                //TODO
                //v.setFocusable(false);
                v.setFocusableInTouchMode(true);
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.d(TAG, ">>>onSaveInstanceState---" + "保存数据");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Log.d(TAG, ">>>onSaveInstanceState---" + "恢复数据");

    }

    public boolean NetState(){
        if(!NetWorkUtils.isNetworkConnected(this)){
            showToast("网络异常，请检查网络是否连接");
            return false;
        }
        return true;
    }

    protected void onRefreshToast(){
        showToast("刷新成功");
    }

    //注册事件
    protected void registEvent(){

    }
    //移除事件
    protected void removeEvent(){

    }
}
